package com.swm.julie.rest.crud.twitt.update;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

import com.swm.julie.rest.crud.twitt.TwittDocFormat;
import com.swm.julie.rest.crud.twitt.search.SearchTwitt;

public class UpdateTwitt {

	String indexDir;
	
	public UpdateTwitt()
	{
		
	}

	/**
	 * update terms of each fields with the id.
	 * @param newTwitt
	 * @return
	 * @throws IOException 
	 * @throws LockObtainFailedException 
	 * @throws CorruptIndexException 
	 */
	public boolean update(TwittDocFormat newTwitt) throws CorruptIndexException, LockObtainFailedException, IOException
	{
		SearchTwitt search = new SearchTwitt();
		search.setIndexDir(indexDir);
		//get old document from the directory to update
		Document doc = search.gethDocument(newTwitt.getId());
		
		IndexWriter writer = new IndexWriter(FSDirectory.open(new File(indexDir)), new IndexWriterConfig(Version.LUCENE_33, new CJKAnalyzer(Version.LUCENE_33)));
		writer.updateDocument(new Term("id", String.valueOf(newTwitt.getId())), doc);
		
		writer.close();
		return true;
	}
	
//	/**
//	 * Return set Document with of the new
//	 * @param newTwitt - to insert
//	 * @return Document - Document of the new twitt
//	 */
//	private Document getDocument(TwittDocFormat newTwitt)
//	{
//		Document doc = new Document();
//		
//		doc.add(new Field("id", String.valueOf(newTwitt.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED));
//		doc.add(new Field("postdate", newTwitt.getPostdate(), Field.Store.YES, Field.Index.ANALYZED));
//		doc.add(new Field("contents", newTwitt.getContents(), Field.Store.YES, Field.Index.ANALYZED));
//		doc.add(new Field("linkInfo", newTwitt.getLinkInfo(), Field.Store.YES, Field.Index.ANALYZED));
//		doc.add(new Field("url", newTwitt.getPostUrl(), Field.Store.YES, Field.Index.ANALYZED));
//		
//		return doc;
//	}
	/**
	 * set a index dir for search.
	 * It must be called before the update for set the dir.
	 * @param indexDir - index directory to update the index
	 */
	public void setIndexDir(String indexDir) {
		this.indexDir = indexDir;
	}
}
